package com.gckj.dfds.backup;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.naming.Name;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @Author liu Weidong
 * @Email:
 * @Date: 2024/5/6 9:45
 * @Version 1.0
 */
public class FetchLogTrailer extends Thread {

    private BackUpNode backUpNode;
    private NameNodeClientRpc nameNodeClientRpc;
    private FSNamesystem fsNamesystem;

    /**
     *  从nameNode拉取log时传递的值
     */
    private Long syncMaxTxid = -1L;

    public FetchLogTrailer(BackUpNode backUpNode, FSNamesystem fsNamesystem,NameNodeClientRpc nameNodeClientRpc) {
        this.backUpNode = backUpNode;// 1117//2786
        this.nameNodeClientRpc = nameNodeClientRpc;
        this.fsNamesystem = fsNamesystem;
    }

    @Override
    public void run() {
        // 进行拉去书
        while (this.backUpNode.isRunning()) {
            try {
                if (!this.fsNamesystem.isFinish()) {
                    // 没有完成初始化工作
                    TimeUnit.MILLISECONDS.sleep(1000);
                    continue;
                }
                if (this.syncMaxTxid < 0) {
                    this.syncMaxTxid = fsNamesystem.getCheckPointerTxid();
                }
                JSONArray jsonArray = nameNodeClientRpc.fetchLog(syncMaxTxid);
                if (jsonArray.size() == 0) {
                    TimeUnit.MILLISECONDS.sleep(1000 * 5);
                    continue;
                }
                for (Object o : jsonArray) {
                    JSONObject jsonObject = (JSONObject) o;
                    System.out.println("拉取到的数据为：" + jsonObject.toString());
                    String op = jsonObject.getString("op");
                    Long txid = jsonObject.getLong("txid");
                    syncMaxTxid = txid;
                    if ("MKDIR".equals(op)) {
                        fsNamesystem.mkdir(jsonObject.getLong("txid"), jsonObject.getString("path"));
                    }
                    if ("CREATE".equals(op)) {
                        fsNamesystem.createFile(jsonObject.getLong("txid"), jsonObject.getString("path"));
                    }
                }
                System.out.println("拉取完一批数据。。。。。。。。。。。");
                TimeUnit.MILLISECONDS.sleep(1000 * 5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
